package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private IFollowService followService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void like(Long blogId) {
        //1. 获取用户的id
        Long userId = UserHolder.getUser().getId();

        //2. 查询是否已被点赞
        String likeKey=BLOG_LIKED_KEY+ blogId;
        Double score = stringRedisTemplate.opsForZSet().score(likeKey, userId.toString());

        if(score!=null){
            //3. 如果已点赞,则取消点赞
            boolean success = update().setSql("liked=liked-1").eq("id", blogId).update();
            if (success) {
                stringRedisTemplate.opsForZSet().remove(likeKey,userId.toString());
            }
        }else{
            //4. 如果未点赞,则点赞
            boolean success = update().setSql("liked=liked+1").eq("id", blogId).update();
            if(success){
                stringRedisTemplate.opsForZSet().add(likeKey,userId.toString(),System.currentTimeMillis());
            }
        }

    }

    @Override
    public Result queryBlogLikes(Long id) {
        //1. 查询最近的5个id
        Set<String> idSet = stringRedisTemplate.opsForZSet().reverseRange(BLOG_LIKED_KEY+id, 0, 4);
        if (idSet==null||idSet.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }

        //2. 解析userId
        List<Long> idList = idSet.stream().map(Long::parseLong).collect(Collectors.toList());
        String idStr = CollectionUtil.join(idList, ",");

        //3. 根据id查询用户信息
        List<User> userList = userService.query().in("id", idList).last("ORDER BY FIELD (id," + idStr + ")").list();
        List<UserDTO> userDTOS = BeanUtil.copyToList(userList, UserDTO.class);

        //4. 返回
        return Result.ok(userDTOS);
    }

    @Override
    public Result queryBlogOfFollow(Long lastId, Integer offset) {
        //1. 获取参数
        Long userId = UserHolder.getUser().getId();

        //2. 获取消息盒中的消息
        // ZREVRANGEBYSCORE key max min WITHSCORES LIMIT offset count
        String key=RedisConstants.FEED_KEY_PREFIX+userId;
        Set<ZSetOperations.TypedTuple<String>> tupleSet = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, lastId, offset, 3);
        if (tupleSet==null||tupleSet.isEmpty()) {
            return Result.ok();
        }
        List<Long> blogIdList=new ArrayList<>();
        long minTime=0L;
        int minCount=1;
        for (ZSetOperations.TypedTuple<String> tuple : tupleSet) {
            // 收集id
            blogIdList.add(Long.parseLong(tuple.getValue()));
            // 处理score
            long time = tuple.getScore().longValue();
            if(minTime==time){
                minCount++;
            }else{
                minTime=time;
                minCount=1;
            }
        }

        //3. 根据id查询博客
        String idStr = StrUtil.join(",", blogIdList);
        List<Blog> blogList = query().in("id", blogIdList).last("ORDER BY FIELD (id," + idStr + ")").list();

        //4. 填充冗余
        for (Blog blog : blogList) {
            //4.1. 查询用户
            queryBlogUser(blog);

            //4.2. 查询是否点赞
            isBlogLiked(blog);
        }

        //5. 结果返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(minCount);

        return Result.ok(scrollResult);
    }

    @Override
    public Result queryById(Long id) {
        //1. 根据id查询blog
        Blog blog = this.getById(id);
        if(blog==null){
            return Result.fail("博客不存在");
        }

        //2. 查询用户
        queryBlogUser(blog);

        //3. 查询是否点赞
        isBlogLiked(blog);

        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        //1. 获取用户的id
        UserDTO user = UserHolder.getUser();
        if (user==null) {
            return;
        }
        Long userId = user.getId();

        //2. 查询是否已被点赞
        String likeKey= BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(likeKey, userId.toString());

        blog.setIsLike(score!=null);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public Result queryHot(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog->{
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });

        return Result.ok(records);
    }

    @Override
    public Result saveBlog(Blog blog) {

        //1. 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //2. 保存探店博文
        boolean success = save(blog);
        if (!success) {
            return Result.ok("创建笔记失败");
        }

        //3. 查询当前用户的粉丝集合
        List<Follow> followList = followService.query().eq("follow_user_id", user.getId()).list();

        //4. 推送消息给粉丝
        for (Follow follow : followList) {
            String feedKey= RedisConstants.FEED_KEY_PREFIX+follow.getUserId();
            stringRedisTemplate.opsForZSet().add(feedKey,blog.getId().toString(),System.currentTimeMillis());
        }

        // 返回id
        return Result.ok(blog.getId());
    }
}
